package com.hiyee.cart.service.impl;

import com.hiyee.api.config.ThreadLocalHolder;
import com.hiyee.api.controller.goods.GoodsControllerApi;
import com.hiyee.api.service.BaseService;
import com.hiyee.cart.mapper.CartItemMapper;
import com.hiyee.cart.mapper.CartMapper;
import com.hiyee.cart.repository.CartRepository;
import com.hiyee.cart.service.CartService;
import com.hiyee.enums.CartUpdateActionEnum;
import com.hiyee.exception.GraceException;
import com.hiyee.pojo.Cart;
import com.hiyee.pojo.CartItem;
import com.hiyee.pojo.Product;
import com.hiyee.pojo.auth.CustomerTokenInfo;
import com.hiyee.pojo.bo.CartAddBO;
import com.hiyee.pojo.bo.CartDeleteBO;
import com.hiyee.pojo.bo.CartUpdateBO;
import com.hiyee.pojo.repo.CartCheckoutRepo;
import com.hiyee.pojo.repo.CartInfoRepo;
import com.hiyee.pojo.repo.GoodsInfoRepo;
import com.hiyee.pojo.vo.CartAddVO;
import com.hiyee.response.ResponseJsonResult;
import com.hiyee.response.ResponseStatusEnum;
import com.hiyee.utils.BigDecimalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class CartServiceImpl extends BaseService implements CartService {

    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private GoodsControllerApi goodsControllerApi;
    @Autowired
    private CartItemMapper cartItemMapper;
    @Autowired
    private CartRepository cartRepo;

    @Override
    public Integer getCartNum(Long customerId) {
        Cart cart = cartMapper.getByCustomerId(customerId);
        if(cart == null) {
            return 0;
        }
        return cart.getTotalQty();
    }

    @Override
    public CartAddVO add(CartAddBO cartAddBO, Long customerId) {
        // 查询货品信息
        ResponseJsonResult result = goodsControllerApi.getInfo(cartAddBO.getGoodsId());
        GoodsInfoRepo goodsInfoRepo = objectMapper.convertValue(result.getData(), GoodsInfoRepo.class);
        // 查询商品信息
        ResponseJsonResult productResult = goodsControllerApi.getProductInfo(cartAddBO.getProductId());
        Product product = objectMapper.convertValue(productResult.getData(), Product.class);
        if(goodsInfoRepo == null || product == null) {
            GraceException.display(ResponseStatusEnum.GOODS_NOT_FOUND);
        }
        // 是否需要校验库存
        if(goodsInfoRepo.getStockManage()) {
            // 判断库存
            if(cartAddBO.getQty() > product.getStockQty()) {
                GraceException.display(ResponseStatusEnum.GOODS_UNDER_STOCK);
            }
        }
        // 加入购物车
        Cart cart = cartMapper.getByCustomerId(customerId);
        // 查询商品是否存在购物车
        CartItem cartItem = cartItemMapper.getByCartAndProduct(cart.getCartId(), cartAddBO.getProductId());
        int addResult = 0;
        if(cartItem == null) {
            // 加入购物车
            cartItem = new CartItem();
            cartItem.setCartId(cart.getCartId());
            cartItem.setItemId(snowflakeIdUtil.nextId());
            cartItem.setGoodsId(cartAddBO.getGoodsId());
            cartItem.setProductId(cartAddBO.getProductId());
            cartItem.setGoodsBn(goodsInfoRepo.getGoodsBn());
            cartItem.setImageUrl(goodsInfoRepo.getImageUrl());
            cartItem.setIsGift(goodsInfoRepo.getIsGift());
            cartItem.setName(goodsInfoRepo.getName());
            cartItem.setIsSelected(1);
            cartItem.setSpecs(product.getSpecs());
            cartItem.setWeight(goodsInfoRepo.getWeight());
            cartItem.setPrice(product.getSalesPrice());
            cartItem.setUnit(goodsInfoRepo.getUnit());
            cartItem.setQtyOrdered(cartAddBO.getQty());
            cartItem.setTotalAmount(BigDecimalUtil.mul(product.getSalesPrice(), BigDecimal.valueOf(cartAddBO.getQty())));
            cartItem.setCreatedAt(new Date());
            cartItem.setUpdatedAt(new Date());
            addResult = cartItemMapper.add(cartItem);
        } else {
            // 更新购物车
            long orderedQty = cartItem.getQtyOrdered() + cartAddBO.getQty();
            BigDecimal totalAmount = BigDecimalUtil.mul(product.getSalesPrice(), BigDecimal.valueOf(orderedQty));
            addResult = cartItemMapper.update(cartItem.getItemId(), orderedQty, totalAmount);
        }
        if(addResult == 0) {
            GraceException.display(ResponseStatusEnum.CART_ADD_FAIL);
        }

        // 重新计算购物车
        cartRepo.recount(cart.getCartId());

        CartAddVO cartAddVO = new CartAddVO();
        cartAddVO.setTotal(cartRepo.getById(cart.getCartId()).getTotalQty());
        return cartAddVO;
    }

    @Override
    public CartInfoRepo getList() {
        return cartRepo.getList();
    }

    @Override
    public Integer update(CartUpdateBO cartUpdateBO) {
        CustomerTokenInfo customerTokenInfo = ThreadLocalHolder.get();
        // 获取购物车
        Cart cart = cartRepo.getByCustomerId(customerTokenInfo.getCustomerId());
        CartItem cartItem = cartItemMapper.getByCartAndProduct(cart.getCartId(), cartUpdateBO.getProductId());
        int ret = 0;
        if(cartUpdateBO.getAction().equals(CartUpdateActionEnum.CHECKED.getLabel())) {
            int isSelected = cartItem.getIsSelected() > 0 ? 0 : 1;
            ret = cartItemMapper.checkProduct(cartItem.getItemId(), isSelected);
        } else if (cartUpdateBO.getAction().equals(CartUpdateActionEnum.DELETE.getLabel())) {
            ret = cartItemMapper.deleteProduct(cartItem.getItemId());
        } else if (cartUpdateBO.getAction().equals(CartUpdateActionEnum.CHANGE.getLabel())) {
            ret = cartItemMapper.updateProduct(cartItem.getItemId(), cartUpdateBO.getQty());
        }
        if(ret == 0) {
            GraceException.display(ResponseStatusEnum.CART_UPDATE_FAIL);
        }
        // 重新计算购物车
        cartRepo.recount(cart.getCartId());
        return cartMapper.getById(cart.getCartId()).getTotalQty();
    }

    @Override
    public Integer delete(CartDeleteBO cartDeleteBO) {
        CustomerTokenInfo customerTokenInfo = ThreadLocalHolder.get();
        Cart cart = cartRepo.getByCustomerId(customerTokenInfo.getCustomerId());
        int ret = cartItemMapper.deleteByProductId(cart.getCartId(), cartDeleteBO.getProductId());
        if(ret == 0) {
            GraceException.display(ResponseStatusEnum.CART_DELETE_FAIL);
        }
        // 重新计算购物车
        cartRepo.recount(cart.getCartId());
        return cartRepo.getById(cart.getCartId()).getTotalQty();
    }

    @Override
    public CartCheckoutRepo checkout() {
        // 获取当前登录用户
        CustomerTokenInfo customerTokenInfo = ThreadLocalHolder.get();
        // 获取购物车
        return cartRepo.getCheckoutGoodsByCustomerId(customerTokenInfo.getCustomerId());
    }
}
